package controller

import (
	"github.com/gin-gonic/gin"
	"jsjb/app/jsjb/model"
	"jsjb/tools"
	"net/http"
)

func SetAdmin(c *gin.Context) {
	var admins model.Admin
	if err := c.ShouldBind(&admins); err == nil {
		_, err := model.SetAdmin(&admins)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"err": err,
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"msg": "插入成功",
		})
	} else {
		c.JSON(http.StatusBadRequest, gin.H{
			"err": err.Error(),
		})
	}
}

func UpdateAdmin(c *gin.Context) {
	var admins model.Admin
	if err := c.ShouldBind(&admins); err == nil {

		err = model.UpdateAdmin(&admins)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"err": err.Error(),
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"msg": "更新成功",
		})
		return
	} else {
		c.JSON(http.StatusBadRequest, gin.H{
			"err": err.Error(),
		})
		return
	}
}

func DeleteAdmin(c *gin.Context) {
	var adminIds []int32
	ids := c.PostForm("admin_id")
	if ids == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"err": "缺少必要的用户id",
		})
		return
	}
	adminIds = tools.StringToSliceInt32(ids)
	err := model.DeleteAdmins(adminIds)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"err": err.Error(),
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"msg": "删除成功!",
		})
		return
	}
}

func QueryAdmin(c *gin.Context) {
	var s model.SearchAdmin
	if err := c.ShouldBind(&s); err == nil {
		if s.PageNo == 0 || s.PageSize == 0 {
			c.JSON(http.StatusBadRequest, gin.H{
				"err": "pageSize,pageNo必传",
			})
			return
		}
		admins, _ := model.QueryAdmins(s)
		c.JSON(http.StatusBadRequest, gin.H{
			"data": admins,
		})
		return

	} else {
		c.JSON(http.StatusBadRequest, gin.H{
			"err": err.Error(),
		})
		return
	}

}
